package com.cndw.kungfu.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;

import com.cndw.commons.util.BlankUtils;
import com.cndw.commons.util.DateFormatUtils;
import com.cndw.kungfu.comm.AccessFlag;
import com.cndw.kungfu.comm.tencent.LogFieldType;
import com.cndw.kungfu.comm.tencent.QQDC;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsConfig;
import com.cndw.kungfu.config.ConstantsCost;
import com.cndw.kungfu.config.ConstantsDailyItem;
import com.cndw.kungfu.config.ConstantsDayIntKey;
import com.cndw.kungfu.config.ConstantsExpRet;
import com.cndw.kungfu.config.ConstantsFlag;
import com.cndw.kungfu.config.ConstantsIntKey;
import com.cndw.kungfu.config.ConstantsLevel;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.config.ConstantsQueue;
import com.cndw.kungfu.config.ConstantsTask;
import com.cndw.kungfu.config.DiscipleConfig;
import com.cndw.kungfu.config.GoodsEffectConfig;
import com.cndw.kungfu.domain.Collect;
import com.cndw.kungfu.domain.Goods;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.Livery;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.PlayerOffline;
import com.cndw.kungfu.domain.Queue;
import com.cndw.kungfu.domain.Scene;
import com.cndw.kungfu.domain.Undercity;
import com.cndw.kungfu.event.once.PlayerPayTask;
import com.cndw.kungfu.ext.JsonProcesser;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.MD5;
import com.cndw.kungfu.ext.NumberProcesser;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.disciple.PlayerMartial;
import com.cndw.kungfu.model.disciple.domain.Disciple;
import com.cndw.kungfu.model.disciple.domain.DiscipleCompararor;
import com.cndw.kungfu.model.general.GeneralManager;
import com.cndw.kungfu.model.general.ModeExpConfig;
import com.cndw.kungfu.model.goods.PlayerBoxs;
import com.cndw.kungfu.model.pvp.LiveryManager;
import com.cndw.kungfu.model.pvp.OnlineExpAnimaWrest;
import com.cndw.kungfu.model.pvp.camp.CampConfig;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.vo.CollectVO;
import com.cndw.kungfu.vo.PlayerReceiveVO;
import com.cndw.kungfu.vo.goodsvo.GoodsVO;
import com.cndw.openqq.client.ClientRequest;
import com.cndw.openqq.client.ClientURI;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 通用控制器
 * 
 * 
 * @author <a href="mailto:whz-work@163.com">汪洪州</a>
 * 
 * @since 1.0 Create on 2011-8-2
 */
@Controller
public class GeneralController {

	@Resource
	private GeneralManager generalManager;

	@Autowired
	private LiveryManager liveryManager;

	/**
	 * 获取祈福信息
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage getPrayInfo(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int currentCounts = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.prayCounts);
		int max = ConstantsModel.prayVipCounts[player.getKnightTrueLevel()];
		int ext = player.getDataInfo().intDataGet(ConstantsIntKey.payCash) / 100000 * 100;
		ext = ext >= 800  ? 800 : ext;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("cur", currentCounts);
		resultMap.put("addAsset", player.getLevel() * ConstantsModel.prayAsset);
		resultMap.put("reqGold", generalManager.getPrayGoldBath(currentCounts, 1));
		int nextBatchTimes = NumberProcesser.between(10, 1, max+ext - currentCounts);
		resultMap.put("batchGold", generalManager.getPrayGoldBath(currentCounts, nextBatchTimes));
		resultMap.put("batchTimes", nextBatchTimes);
		resultMap.put("max", max);
		resultMap.put("ext", ext);
		QQDC.getInstance().logClick(player, LogFieldType.caishen);

		return ResponseMessage.getSuccMessage(resultMap);
	}

	/**
	 * 祈福
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage exchangePray(Session session, boolean batch) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int max = ConstantsModel.prayVipCounts[player.getKnightTrueLevel()];
		int ext = player.getDataInfo().intDataGet(ConstantsIntKey.payCash) / 100000 * 100;
		ext = ext >=800 ? 800 : ext;
		int haveTimes = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.prayCounts);
		int currentTimes = batch ? 10 : 1;
		currentTimes = NumberProcesser.between(currentTimes, 1, max+ext - haveTimes);
		if (haveTimes + currentTimes > max+ext || currentTimes <= 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.exchangePray.counts", max));
		}

		int gold = generalManager.getPrayGoldBath(haveTimes, currentTimes);
		if (player.getGoldAll() < gold) {
			return ResponseMessage.getSuccMessage(false);
		}
		int currentCounts = haveTimes + currentTimes;

		int asset = player.getLevel() * ConstantsModel.prayAsset * currentTimes;
		player.alterGoldAll(-gold);
		player.alterAsset(asset);
		player.commitSync();
		player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.prayCounts, currentCounts);
		
		//设置到每日奖励
		player.getDataInfo().getEveryDay().finishDailyItem(ConstantsDailyItem.thanksGodItem);
		
		player.getDataInfo().commitSync();

		LogServer.recordLog(player, ConstantsLog.gold, 50004, gold, asset);
		LogServer.costEventLog(player.getPlayerId(), gold, ConstantsCost.exchangePray);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("cur", currentCounts);
		resultMap.put("addAsset", player.getLevel() * ConstantsModel.prayAsset);
		resultMap.put("addTimes", currentTimes);
		resultMap.put("reqGold", generalManager.getPrayGoldBath(currentCounts, 1));
		int nextBatchTimes = NumberProcesser.between(10, 1, max + ext - currentCounts);
		resultMap.put("batchGold", generalManager.getPrayGoldBath(currentCounts, nextBatchTimes));
		resultMap.put("batchTimes", nextBatchTimes);
		resultMap.put("max", ConstantsModel.prayVipCounts[player.getKnightTrueLevel()]);
		resultMap.put("ext", ext);
		resultMap.put("gold", player.getGold());
		resultMap.put("goldBing", player.getGoldBing());
		resultMap.put("asset", player.getAsset());
		return ResponseMessage.getSuccMessage(resultMap);
	}

	/**
	 * 获取在线经验信息
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage getOnlineExpInfo(Session session) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv1OnlineExp) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.onlineExp.minLevel", ConstantsLevel.lv1OnlineExp));
		}

		Scene scene = Context.getSceneServer().getSceneById(player.getSceneId());
		if (!scene.isCityMain()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.onlineExp.scene"));
		}

		int exp = 0;
		for (Integer level : ModeExpConfig.getOnlineExp().keySet()) {
			if (player.getLevel() >= level) {
				exp = ModeExpConfig.getOnlineExp().get(level).intValue();
				break;
			}
		}
		if (exp > 0) {
			int addRate = 0;
			// if (player.getVipLevel() > 0 && player.getVip().getMeditationR()
			// > 0) {
			// addRate += player.getVip().getMeditationR();
			// }
			if (player.getKnight() != null) {
				addRate += player.getKnight().getMeditationR();
			}
			if (addRate > 0) {
				exp = NumberProcesser.percentClac(exp, addRate);
			}
		}

		// 灵气加成
		int animaAddRate = OnlineExpAnimaWrest.getAddRate(player.getPlayerId());
		// if (animaAddRate > 0) {
		// exp = NumberProcesser.percentClac(exp, animaAddRate);
		// }

		player.getDataInfo().intDataSet(ConstantsIntKey.beginDaZuo, TimeProcesser.getUnixTime());
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("interval", ConstantsModel.onlineExpInterval);
		resultMap.put("hours", ConstantsModel.onlineExpHours);
		resultMap.put("exp", exp);
		resultMap.put("addRate", animaAddRate); // 灵气加成比率

		return ResponseMessage.getSuccMessage(resultMap);
	}

	/**
	 * 获取在线打坐经验
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage getOnlineExp(Session session) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv1OnlineExp) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.onlineExp.minLevel", ConstantsLevel.lv1OnlineExp));
		}

		Scene scene = Context.getSceneServer().getSceneById(player.getSceneId());
		if (!scene.isCityMain()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.onlineExp.scene"));
		}

		int exp = Context.getGeneralServer().getOnlineExp(player);
		if (exp > 0) {
			player.commitSync();
		}

		PlayerReceiveVO receive = new PlayerReceiveVO();
		receive.put(PlayerReceiveVO.RECEIVE_EXP, exp);

		if (exp > 0) {
			// 添加帮派“人物-打坐经验”日志
			LogServer.recordLog(player, ConstantsLog.player, 30003, exp);
		}

		return ResponseMessage.getSuccMessage(receive);
	}

	/**
	 * 获取用户离线经验相关信息
	 * 
	 * @return
	 */
	public ResponseMessage getOfflineExpInfo(Session session) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv27OfflineExp) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.exchange.minLevel", ConstantsLevel.lv27OfflineExp));
		}

		PlayerBoxs playerBox = player.getPlayerBoxs();
		Map<Object, Object> resultMap = new HashMap<Object, Object>();
		for (int goodsId : GoodsEffectConfig.getOfflinegoodsids()) {
			GoodsVO goodsVo = Context.getGoodsServer().getModeById(goodsId).toGoodsVO();
			if (!BlankUtils.isBlank(goodsVo)) {
				goodsVo.setStackNum(playerBox.getStackNum(goodsId));
				resultMap.put(((float) goodsVo.getGoodsModeVO().getValueA()) / 10f, goodsVo);
			}
		}

		resultMap.put("counts", ConstantsModel.offlineGetCounts);
		resultMap.put("surplusCounts", generalManager.getSurplusCounts(session.getUid()));
		return ResponseMessage.getSuccMessage(resultMap);
	}

	/**
	 * 获取用户兑换离线经验的道具
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage getOfflineExpGoods(Session session, int goodsId) {

		if (!(goodsId == 103019 || goodsId == 103020 || goodsId == 103021)) {
			return null;
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv27OfflineExp) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.exchange.minLevel", ConstantsLevel.lv27OfflineExp));
		}

		GoodsMode goods = Context.getGoodsServer().getModeById(goodsId);
		if (BlankUtils.isBlank(goods)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		Map<Object, Object> resultMap = new HashMap<Object, Object>();
		for (Integer level : ModeExpConfig.getOfflineExp().keySet()) {
			if (player.getLevel() >= level) {

				Integer[] config = ModeExpConfig.getOfflineExp().get(level);

				// int exp = (int) (config[1] * goods.getValueA() / 10f);
				int exp = config[1];
				/*
				 * if (!BlankUtils.isBlank(player.getKnight())) { exp =
				 * NumberProcesser.percentClac(exp,
				 * player.getKnight().getLineUseExpR()); }
				 */

				resultMap.put("level", player.getLevel());
				resultMap.put("exp", exp);
				resultMap.put("goodsCounts", config[0]);
				break;
			}
		}
		Context.getTaskServer().notifyToSpark(session.getUid(), ConstantsTask.spark34OffExp, 1);

		resultMap.put("surplusCounts", generalManager.getSurplusCounts(session.getUid()));

		QQDC.getInstance().logClick(player, LogFieldType.shopExp);

		return ResponseMessage.getSuccMessage(resultMap);
	}

	/**
	 * 兑换经验
	 */
	public ResponseMessage exchange(Session session, int goodsId) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv27OfflineExp) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.exchange.minLevel", ConstantsLevel.lv27OfflineExp));
		}

		GoodsMode goods = Context.getGoodsServer().getModeById(goodsId);
		if (BlankUtils.isBlank(goods)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		} else {
			// if (player.getVipLevel() > 0) {
			// if (goods.getValueA() == 15 &&
			// !player.getVip().isOpenOffLine15()) {
			// return
			// ResponseMessage.ticpErrMsg(LanguageLib.get("general.exchange.15"));
			// } else if (goods.getValueA() == 20 &&
			// !player.getVip().isOpenOffLine20()) {
			// return
			// ResponseMessage.ticpErrMsg(LanguageLib.get("general.exchange.20"));
			// }
			// }
		}

		int exp = 0;

			int surplusCounts = generalManager.getSurplusCounts(session.getUid());
			if (surplusCounts <= 0) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("general.exchange.daymax"));
			}

			int counts = 0;
			for (Integer level : ModeExpConfig.getOfflineExp().keySet()) {
				if (player.getLevel() >= level) {
					Integer[] config = ModeExpConfig.getOfflineExp().get(level);
					exp = config[1];
					counts = config[0];

					exp = (int) (config[1] * goods.getValueA() / 10f);
					/*
					 * if (!BlankUtils.isBlank(player.getKnight())) { exp =
					 * NumberProcesser.percentClac(exp,
					 * player.getKnight().getLineUseExpR()); }
					 */
					break;
				}
			}

			PlayerBoxs playerBox = player.getPlayerBoxs();
			if (counts <= 0 || playerBox.getStackNum(goodsId) < counts) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("general.exchange.goods"));
			}

			playerBox.costGoods(goodsId, counts);
			player.alterExp((int) exp);
			player.commitSync();// 提交同步

			PlayerOffline offline = new PlayerOffline();
			offline.setGoodsId(goodsId);
			offline.setPlayerId(session.getUid());
			offline.setGetTime(TimeProcesser.getUnixTime());
			generalManager.addOfflineExp(offline);

			// 添加“人物-离线经验”日志
			GoodsMode mode = Context.getGoodsServer().getModeById(goodsId);
			LogServer.recordLog(player, ConstantsLog.player, 30002, ((float) mode.getValueA()) / 10f, mode.getName(), counts, exp);
		
		PlayerReceiveVO receive = new PlayerReceiveVO();
		receive.put(PlayerReceiveVO.RECEIVE_EXP, exp);
		player.getDataInfo().getEveryDay().finishDailyItem(ConstantsDailyItem.useExpDrugItem);

		return ResponseMessage.getSuccMessage(receive);
	}

	/**
	 * 获取用户宝鉴的所有信息
	 * 
	 * @param session
	 * @param type
	 *            1道具类(11:消耗品，12:丹药)，2装备类(21:武者装备，22:气宗装备，23:药师装备)，3秘籍类(31:内功书
	 *            ，32:秘籍)，4徒弟类(41:徒弟技能书，42:徒弟消耗品)
	 * @return
	 */
	public ResponseMessage getCollectByType(Session session, int type) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		if (player.getLevel() < ConstantsLevel.lv18Collect) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.collect.level", ConstantsLevel.lv18Collect));
		}

		// 统计包袱物品
		Map<Integer, Integer> goodsCounts = new HashMap<Integer, Integer>();
		PlayerBoxs playerBoxs = player.getPlayerBoxs();
		synchronized (playerBoxs) {
			for (Goods g : playerBoxs.getBoxsGoods()) {
				if (!playerBoxs.isLocked(g.getStoragePlace())) {
					if (goodsCounts.containsKey(g.getGoodsId())) {
						goodsCounts.put(g.getGoodsId(), goodsCounts.get(g.getGoodsId()) + g.getStackNum());
					} else {
						goodsCounts.put(g.getGoodsId(), g.getStackNum());
					}
				}
			}
		}

		List<CollectVO> collectVOs = new ArrayList<CollectVO>();
		if (type > 10) { // 根据子类型获取宝鉴
			List<Collect> collects = Context.getGeneralServer().getCollectByType(type);
			if (!BlankUtils.isBlank(collects)) {
				for (Collect collect : collects) {
					collectVOs.add(collect.toCollectVO(session.getUid(), goodsCounts));
				}
			}
		} else { // 根据大类型获取宝鉴
			Collection<Collect> collects = Context.getGeneralServer().getCollects();
			if (!BlankUtils.isBlank(collects)) {
				String typeString = String.valueOf(type);
				for (Collect collect : collects) {
					if (String.valueOf(collect.getType()).startsWith(typeString)) {
						collectVOs.add(collect.toCollectVO(session.getUid(), goodsCounts));
					}
				}
			}
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("collects", collectVOs);
		resultMap.put("points", player.getPoints());
		return ResponseMessage.getSuccMessage(resultMap);
	}

	/**
	 * 兑换图鉴
	 * 
	 * @param session
	 * @param collectId
	 * @return
	 */
	public ResponseMessage exchangeCollect(Session session, int collectId) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv18Collect) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.collect.level", ConstantsLevel.lv18Collect));
		}

		Collect collect = Context.getGeneralServer().getCollect(collectId);
		if (BlankUtils.isBlank(collect)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.collect.null"));
		}

		PlayerBoxs playerBoxs = player.getPlayerBoxs();
		synchronized (playerBoxs) {

			// 获取以前是否兑换过
			boolean exchanged = generalManager.checkCollectFinish(player.getPlayerId(), collectId);

			// 检查是否为可重复兑换的图鉴
			if (!collect.isReiteration() && exchanged) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("general.collect.repeat"));
			}

			// 统计包袱物品
			Map<Integer, Integer> goodsCounts = new HashMap<Integer, Integer>();
			for (Goods g : playerBoxs.getBoxsGoods()) {
				if (!playerBoxs.isLocked(g.getStoragePlace())) {
					if (goodsCounts.containsKey(g.getGoodsId())) {
						goodsCounts.put(g.getGoodsId(), goodsCounts.get(g.getGoodsId()) + g.getStackNum());
					} else {
						goodsCounts.put(g.getGoodsId(), g.getStackNum());
					}
				}
			}

			// 检查是否收集完成
			if (Context.getGeneralServer().checkProgress(goodsCounts, collect) != 100) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("general.collect.exist"));
			}

			// 检查包袱是否足够
			if (!playerBoxs.checkBlack(collect.getCounts())) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", collect.getCounts()));
			}

			// 扣掉收集材料
			StringBuilder log = new StringBuilder();

			int bindType = playerBoxs.costGoods(collect.getGoodsId1(), collect.getCounts1());
			GoodsMode mode = Context.getGoodsServer().getModeById(collect.getGoodsId1());
			log.append(mode.getName()).append("*").append(collect.getCounts1());

			if (collect.getGoodsId2() > 0) {// goods 2
				bindType += playerBoxs.costGoods(collect.getGoodsId2(), collect.getCounts2());
				mode = Context.getGoodsServer().getModeById(collect.getGoodsId2());
				log.append(mode.getName()).append("*").append(collect.getCounts2());
			}
			if (collect.getGoodsId3() > 0) {// goods 3
				bindType += playerBoxs.costGoods(collect.getGoodsId3(), collect.getCounts3());
				mode = Context.getGoodsServer().getModeById(collect.getGoodsId3());
				log.append(mode.getName()).append("*").append(collect.getCounts3());
			}
			if (collect.getGoodsId4() > 0) {// goods 4
				bindType += playerBoxs.costGoods(collect.getGoodsId4(), collect.getCounts4());
				mode = Context.getGoodsServer().getModeById(collect.getGoodsId4());
				log.append(mode.getName()).append("*").append(collect.getCounts4());
			}
			if (collect.getGoodsId5() > 0) { // goods 5
				bindType += playerBoxs.costGoods(collect.getGoodsId5(), collect.getCounts5());
				mode = Context.getGoodsServer().getModeById(collect.getGoodsId5());
				log.append(mode.getName()).append("*").append(collect.getCounts5());
			}

			// 发放兑换物品
			mode = Context.getGoodsServer().getModeById(collect.getGoodsId());
			Context.getGoodsServer().giveGoodsBing(player.getPlayerId(), collect.getGoodsId(), collect.getCounts(), bindType >= 1 ? 1 : 0);

			// 记录兑换
			if (exchanged) {
				generalManager.increasePlayerCollect(player.getPlayerId(), collectId);
			} else {
				generalManager.addPlayerCollect(player.getPlayerId(), collectId);
			}
			Context.getTaskServer().notifyToSpark(player.getPlayerId(), ConstantsTask.spark22Collect, 1);

			// 增加成就点
			player.setPoints(player.getPoints() + collect.getPoints());
			player.commitSync();

			LogServer.recordLog(player, ConstantsLog.goods, 70019, log.toString(), mode.getName(), collect.getCounts(), collect.getPoints());

			return ResponseMessage.getSuccMessage(player.getPoints());
		}
	}

	/**
	 * FAQ 获取签名
	 * 
	 * @param session
	 * @param gameId
	 * @param unique
	 * @param time
	 * @return
	 */
	public ResponseMessage getFAQSign(Session session, int gameId, String unique) {
		int timestamp = TimeProcesser.getUnixTime();
		String sign = MD5.compile(String.valueOf(timestamp) + gameId + unique + "tencent-gm-1cfcc74b-b0e6-456b-8c8e-a0169394acc7");

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("timestamp", timestamp);
		resultMap.put("sign", sign);
		return ResponseMessage.getSuccMessage(resultMap);
	}

	/**
	 * 领取卡
	 * 
	 * @param session
	 * @param secretKey
	 * @return
	 */
	public ResponseMessage exchangeCard(Session session, String secretKey) {

		if (BlankUtils.isBlank(secretKey) || (secretKey.length() != 36 && secretKey.length() != 10)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.exchangeCard.secretKey"));
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int timestamp = TimeProcesser.getUnixTime();

		// sign=action+timestamp+key
		StringBuilder sign = new StringBuilder("exchange");
		sign.append(timestamp);
		sign.append(ConstantsConfig.getSysCgKeyPlatform());

		try {
			// Data
			StringBuilder data = new StringBuilder();
			data.append("secretKey=");
			data.append(secretKey);
			data.append("&serverId=");
			data.append(ConstantsConfig.getSysCgSvrId());
			data.append("&playerId=");
			data.append(player.getPlayerId());
			data.append("&playerAccount=");
			data.append(player.getAccountName());
			data.append("&playerName=");
			data.append(player.getPlayerName());
			data.append("&registerTime=");
			data.append(player.getRegTime());
			data.append("&counts=");
			data.append(player.getPlayerBoxs().getBlackNumbers());
			data.append("&timestamp=");
			data.append(timestamp);
			data.append("&sign=");
			data.append(MD5.compile(sign.toString()));

			// connect
			HttpURLConnection urlConnection = (HttpURLConnection) new URL(ConstantsConfig.getSysCgCrossURL() + "gift?action=exchange").openConnection();
			urlConnection.setUseCaches(false);
			urlConnection.setDoOutput(true);
			urlConnection.setConnectTimeout(3000);

			// write
			PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "utf-8"));
			printWriter.write(data.toString());
			printWriter.flush();
			printWriter.close();

			// read
			String temp;
			StringBuilder result = new StringBuilder();
			InputStream inputStream = urlConnection.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
			while ((temp = reader.readLine()) != null) {
				result.append(temp);
			}

			ObjectMapper mapper = new ObjectMapper();
			JsonNode node = mapper.readValue(result.toString(), JsonNode.class);

			// exception check
			JsonNode statusNode = node.get("status");
			if (statusNode.asInt() == 0) {
				return ResponseMessage.ticpErrMsg(node.get("info").asText());
			}
			player.getDataInfo().getEveryDay().setPveBug(0);// 通过礼品卡的方式清理pve外挂标记

			JsonNode dataNode = node.get("data");
			if (dataNode.isContainerNode()) {

				List<Integer[]> goodsList = new ArrayList<Integer[]>();
				Iterator<JsonNode> iterator = mapper.readValue(dataNode.get("goods").asText(), JsonNode.class).iterator();
				while (iterator.hasNext()) {
					JsonNode goods = iterator.next();
					goodsList.add(new Integer[] { goods.get("goodsId").asInt(), goods.get("num").asInt(), goods.get("bind").asInt() });
				}

				StringBuilder content = new StringBuilder(LanguageLib.get("general.exchangeCard.content", DateFormatUtils.getFormatDateTime(), secretKey));
				Map<String, Object> resultMap = new HashMap<String, Object>();

				// 给元宝
				int goldValue = dataNode.get("goldValue").asInt();
				if (goldValue != 0) {
					player.receiveGold(goldValue);
					resultMap.put("gotGold", goldValue);
					content.append(LanguageLib.get("general.exchangeCard.gold"));
					content.append(goldValue);
					content.append("<br/>");

					int exchangeType = dataNode.get("exchangeType").asInt();
					int sysCgPayRate = ConstantsConfig.getSysCgPayRate() == 0 ? 10 : ConstantsConfig.getSysCgPayRate();
					Context.getBusinessServer().payInsertDB(player, secretKey.concat("-" + String.valueOf(player.getPlayerId())), goldValue / sysCgPayRate,
							goldValue, exchangeType);
					if (exchangeType == 1) {
						PlayerPayTask command = new PlayerPayTask(player);
						Context.getTimerServer().execute(command);
					} else if (exchangeType == 3) {
						PlayerPayTask command = new PlayerPayTask(player);
						Context.getTimerServer().execute(command);
						player.getDataInfo().intDataSet(ConstantsIntKey.payFree, 1);
						player.getDataInfo().commitSync();// 类型为3的充值为测试帐号
					}
				}

				// 给银票
				int goldTickeValue = dataNode.get("goldTickeValue").asInt();
				if (goldTickeValue != 0) {
					player.alterGoldTicke(goldTickeValue);
					resultMap.put("gotGoldTicke", goldTickeValue);
					content.append(LanguageLib.get("general.exchangeCard.goldTicke"));
					content.append(goldTickeValue);
					content.append("<br/>");
				}

				// 给银两
				int assetValue = dataNode.get("assetValue").asInt();
				if (assetValue != 0) {
					player.alterAsset(assetValue);
					resultMap.put("gotAsset", assetValue);
					content.append(LanguageLib.get("general.exchangeCard.asset"));
					content.append(assetValue);
					content.append("<br/>");
				}

				// 给道具
				StringBuffer logSb = new StringBuffer();
				for (Integer[] goods : goodsList) {
					Context.getGoodsServer().giveGoodsBing(player.getPlayerId(), goods[0], goods[1], goods[2]);
					GoodsMode goodsMode = Context.getGoodsServer().getModeById(goods[0]);
					if (goodsMode != null) {
						content.append(goodsMode.getName()).append("*").append(goods[1]).append("<br/>");
						logSb.append("|" + goodsMode.getName() + ":" + goods[1]);
					}
				}
				resultMap.put("gold", player.getGold());
				resultMap.put("asset", player.getAsset());
				resultMap.put("goldTicke", player.getGoldTicke());

				// 发送事件
				Context.getMessageServer().recordEvent(player.getPlayerId(), LanguageLib.get("general.exchangeCard.title"), content.toString(),
						Constants.eventTypeExchange);

				// 添加“领取礼包”日志
				LogServer.recordLog(player, ConstantsLog.goods, 70011, secretKey, goldTickeValue, goldValue, assetValue, logSb.toString());

				return ResponseMessage.getSuccMessage(resultMap);
			}
		} catch (IOException e) {
			LogUtil.getMain().error("err:" + e.getMessage());
			e.printStackTrace();
		}
		return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.sys"));
	}

	public ResponseMessage exchangeCDK(Session session, String cdk) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (cdk == null || cdk.length() != 16) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("activity.giftcdk.length"));
		}
		int timestamp = TimeProcesser.getUnixTime();

		StringBuilder data = new StringBuilder();
		//data.append("http://localhost:8080/gfhome/");
		data.append(ConstantsConfig.getSysCgCrossURL());
		data.append("gift?action=cdk");
		data.append("&playerId=").append(player.getPlayerId());
		data.append("&playerAccount=").append(player.getAccountName());
		data.append("&playerName=").append(player.getPlayerName());
		data.append("&serverId=").append(ConstantsConfig.getSysCgSvrId());
		data.append("&cdk=").append(cdk);

		data.append("&counts=").append(player.getPlayerBoxs().getBlackNumbers());
		data.append("&timestamp=").append(timestamp);
		data.append("&s=").append(Math.random());

		// sign=action+timestamp+key
		StringBuilder sign = new StringBuilder("cdk");
		sign.append(timestamp);
		sign.append(ConstantsConfig.getSysCgKeyPlatform());

		data.append("&sign=").append(MD5.compile(sign.toString()));

		URI uri = ClientURI.createURI(data.toString());
		String apiMsg = null;
		try {
			apiMsg = ClientRequest.sendGetRequest(uri, 3000, 8000);
			if (apiMsg == null) {
				LogUtil.getMain().debug("request time out");
				return null;
			}
			Map<String, String> resultMap = JsonProcesser.objectJsonMapDecode(apiMsg, String.class, String.class);
			if (resultMap.containsKey("info") && resultMap.get("info") != null && resultMap.get("info").trim().length() > 0) {
				return ResponseMessage.ticpErrMsg(resultMap.get("info").trim());
			}
			int ret = Integer.valueOf(resultMap.get("data").toString());
			int awardId = 0;
			if (ret == 1) {
				awardId = 103513;
			} else if (ret == 2) {
				awardId = 103514;
			} else if (ret == 3) {
				awardId = 103516;
			}else {
				return null;
			}
			Context.getGoodsServer().giveGoodsBing(player.getPlayerId(), awardId, 1, 1);
			GoodsMode goodsMode = Context.getGoodsServer().getModeById(awardId);
			LogServer.recordLog(player, ConstantsLog.goods, 70026, goodsMode.getName());

		} catch (Exception e) {
			e.printStackTrace();
			return ResponseMessage.getSuccMessage(false);
		}

		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 显示经验找回列表
	 * 
	 * @param session
	 * @return ResponseMessage
	 * @author Skycat
	 */
	public ResponseMessage showExpRetList(Session session) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		// 30 级开放
		if (player.getLevel() < ConstantsLevel.lv27ExpRetrieve) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.exchange.minLevel", ConstantsLevel.lv27ExpRetrieve));
		}

		// 获取玩家三天内未完成活动列表
		Map<Object, Object> rtMap = new HashMap<Object, Object>();
		int day = TimeProcesser.getMorningTime(); // 当天凌晨时间
		List<HashMap<Object, Object>> list = new ArrayList<HashMap<Object, Object>>();
		rtMap.put("list", list);
		rtMap.put("rate", ConstantsExpRet.retAssetCostBase); // 银两比率
		for (int i = 1; i <= 3; i++) {
			day = day - 86400;
			int[] arr = player.getDataInfo().getExpRetrieve(day);
			int subDay = (player.getRegTime() - day) / 86400;
			if (null == arr || subDay > 0) {
				continue;
			}

			for (int pos = 1; pos < arr.length; pos++) {
				int exp = 0, gold = 0, achiveRet = 0;
				if (arr[0] < ConstantsLevel.lv27ExpRetrieve) {
					continue;
				}
				if (pos == Constants.expRet_dart) { // 押镖：剩余押镖次数 * 该等级押镖经验
					int leaveTimes = ConstantsExpRet.expRetMaxTimes[pos] - arr[pos];
					if (player.getKnightTrueLevel() == 4) {
						// 黄金武状元增加1次押镖次数
						leaveTimes += 1;
					}
					if ((leaveTimes < 1) || (arr[0] < ConstantsLevel.lv35Dart)) {
						continue;
					}
					exp = leaveTimes * ConstantsExpRet.expRetDart[arr[0] - ConstantsLevel.lv35Dart];
					gold = (int) (leaveTimes * ConstantsExpRet.expRetDartCostBase * 1.5);
				} else if (pos == Constants.expRet_sbz) { // 神兵阵跳关经验,
															// 跳关到当前已打到神兵阵关数 *
															// 剩余次数
					int leaveTimes = ConstantsExpRet.expRetMaxTimes[pos] - arr[pos];
					if (leaveTimes < 1 || (arr[0] < ConstantsLevel.lv28sbz)) {
						continue;
					}
					int soldierLevel = player.getDataInfo().intDataGet(ConstantsIntKey.soldierCpPass);
					int index = (soldierLevel / 10 + 1) * 2 - 1;
					if (index > 19) {
						index = 19;
					}
					exp = ConstantsModel.undercityScpExpAdd[index] * leaveTimes;
					gold = (int) (leaveTimes * ConstantsExpRet.expRetSbzCost * 1.5);
				} else if (pos == Constants.expRet_wall) { // 远古塞外
					if ((arr[pos] >= ConstantsExpRet.expRetMaxTimes[pos]) || (arr[0] < ConstantsLevel.lv42Wall)) {
						continue;
					}
					exp = ConstantsExpRet.expRetWall[arr[0] - ConstantsLevel.lv42Wall][0];
					gold = ConstantsExpRet.expRetWall[arr[0] - ConstantsLevel.lv42Wall][1];
				} else if ((pos == Constants.expRet_boosYtz) || (pos == Constants.expRet_boosBear) || (pos == Constants.expRet_boosCyh)) { // 3个野外boss
					if ((arr[pos] >= ConstantsExpRet.expRetMaxTimes[pos]) || (arr[0] < ConstantsLevel.lv30Boss)) {
						continue;
					}
					exp = ConstantsExpRet.expRetBoss[arr[0] - ConstantsLevel.lv30Boss][0];
					gold = ConstantsExpRet.expRetBoss[arr[0] - ConstantsLevel.lv30Boss][1];
				} else if (pos == Constants.expRet_unionBat) { // 帮派战
					if (arr[pos] >= ConstantsExpRet.expRetMaxTimes[pos]) { // (arr[0]
																			// <
																			// ConstantsLevel.lv23UnionCreate)
																			// 帮派战开放等级小于经验找回开放等级
						continue;
					}
					if (player.getUnionId() <= 0) { // 没有参加帮派不能找回
						continue;
					}
					exp = ConstantsExpRet.expRetUnionBat[arr[0] - ConstantsLevel.lv27ExpRetrieve][0];
					gold = ConstantsExpRet.expRetUnionBat[arr[0] - ConstantsLevel.lv27ExpRetrieve][1];
				} else if (pos == Constants.expRet_sit) { // 双倍打坐
					if (arr[pos] >= ConstantsExpRet.expRetMaxTimes[pos]) { // (arr[0]
																			// <
																			// ConstantsLevel.lv1OnlineExp)
						continue;
					}
					exp = ConstantsExpRet.expRetOnline[arr[0] - ConstantsLevel.lv27ExpRetrieve][0];
					gold = ConstantsExpRet.expRetOnline[arr[0] - ConstantsLevel.lv27ExpRetrieve][1];
				} else if (pos == Constants.expRet_quiz) { // 答题
					if (arr[pos] >= ConstantsExpRet.expRetMaxTimes[pos]) { // (arr[0]
																			// <
																			// ConstantsLevel.lv13Quiz)
						continue;
					}
					exp = ConstantsExpRet.expRetQuiz[arr[0] - ConstantsLevel.lv27ExpRetrieve];
					gold = ConstantsExpRet.expRetQuizCost;
				} else if (pos == Constants.achiveRet_warpvp) {//门派战
					if (arr[pos] >= ConstantsExpRet.expRetMaxTimes[pos] || (arr[0] < CampConfig.applyLevel)) {
						continue;
					}
					
					gold = ConstantsExpRet.achiveRetWarpvpCost;
					achiveRet = arr[0] * 18;
				} else if (pos == Constants.achiveRet_cb) {//襄阳保卫战
					if (arr[pos] >= ConstantsExpRet.expRetMaxTimes[pos] || (arr[0] < ConstantsLevel.lv30CityBattle)) {
						continue;
					}
					
					gold = ConstantsExpRet.achiveRetCBCost;
					achiveRet = arr[0] * 20;
				}

				HashMap<Object, Object> map = new HashMap<Object, Object>(5);
				map.put("date", day); // 时间
				map.put("level", arr[0]); // 当前等级
				map.put("type", pos); // 活动类型
				if (exp > 0) {
					map.put("exp", exp); // 找回经验
				}
				if (achiveRet > 0) {
					map.put("achiveRet", achiveRet); // 找回战功
				}
				map.put("gold", gold); // 花费元宝
				list.add(map);
			}
		}

		return ResponseMessage.getSuccMessage(rtMap);
	}

	/**
	 * 经验找回
	 * 
	 * @param session
	 * @param date
	 *            找回日期
	 * @param retType
	 *            找回类型(1银两2元宝)
	 * @param type
	 *            活动类型(1~9)
	 * @return ResponseMessage
	 * @author Skycat
	 */
	@AccessFlag(ConstantsFlag.expRet)
	public ResponseMessage expRetrieve(Session session, long date, int retType, int type) {
		if ((retType != 1) && (retType != 2)) {
			return null;
		}
		if ((type < 1) || (type > 11)) {
			return null;
		}

		int dateTime = (int) date;
		int nowTime = TimeProcesser.getMorningTime(); // 当天凌晨时间
		if (dateTime < 0 || (dateTime >= nowTime) || (dateTime - nowTime) > 86400 * 4) {
			return null;
		}

		int subDay = (nowTime - dateTime) / 86400;
		if (subDay < 1 || subDay > 3) {
			return null;
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv27ExpRetrieve) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.exchange.minLevel", ConstantsLevel.lv27ExpRetrieve));
		}

		// 武状元才能使用元宝找回
		if (retType == 2 && player.getKnightTrueLevel() < 1) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.expRet.needKnight"));
		}
		int rate = 60; // 找回比率
		if (retType == 2) {
			rate = 100;
		}

		// 计算获得经验及消费
		int retArray[] = player.getDataInfo().getExpRetMap().get(dateTime);
		if (null == retArray) {
			return null;
		}
		if (retArray[0] < ConstantsLevel.lv27ExpRetrieve) {
			return null;
		}

		int exp = 0;
		int achiveRet = 0;
		int costGold = 0; // 花费元宝
		int costAsset = 0; // 花费银两
		int leaveTimes = 0;
		switch (type) {
		case Constants.expRet_dart: // 押镖
			leaveTimes = ConstantsExpRet.expRetMaxTimes[type] - retArray[type];
			if (player.getKnightTrueLevel() == 4) {
				// 黄金武状元增加1次押镖次数
				leaveTimes += 1;
			}
			if (leaveTimes < 1 || retArray[0] < ConstantsLevel.lv35Dart) {
				return null;
			}
			exp = leaveTimes * ConstantsExpRet.expRetDart[retArray[0] - ConstantsLevel.lv35Dart] * rate / 100;
			costGold = (int) (leaveTimes * ConstantsExpRet.expRetDartCostBase * 1.5);
			break;
		case Constants.expRet_sbz: // 神兵阵
			leaveTimes = ConstantsExpRet.expRetMaxTimes[type] - retArray[type];
			if (leaveTimes < 1 || retArray[0] < ConstantsLevel.lv28sbz) {
				return null;
			}
			int soldierLevel = player.getDataInfo().intDataGet(ConstantsIntKey.soldierCpPass);
			int index = (soldierLevel / 10 + 1) * 2 - 1;
			if (index > 19) {
				index = 19;
			}
			exp = ConstantsModel.undercityScpExpAdd[index] * leaveTimes * rate / 100;
			costGold = (int) (leaveTimes * ConstantsExpRet.expRetSbzCost * 1.5);
			break;
		case Constants.expRet_wall: // 远古塞外
			if (retArray[type] >= ConstantsExpRet.expRetMaxTimes[type] || retArray[0] < ConstantsLevel.lv42Wall) {
				return null;
			}
			exp = (ConstantsExpRet.expRetWall[retArray[0] - ConstantsLevel.lv42Wall][0]) * rate / 100;
			costGold = ConstantsExpRet.expRetWall[retArray[0] - ConstantsLevel.lv42Wall][1];
			break;
		case Constants.expRet_boosYtz: // boss殷天正
		case Constants.expRet_boosBear: // boss大地暴熊
		case Constants.expRet_boosCyh: // boss崔玉环
			if (retArray[type] >= ConstantsExpRet.expRetMaxTimes[type] || retArray[0] < ConstantsLevel.lv30Boss) {
				return null;
			}
			exp = (ConstantsExpRet.expRetBoss[retArray[0] - ConstantsLevel.lv30Boss][0]) * rate / 100;
			costGold = ConstantsExpRet.expRetBoss[retArray[0] - ConstantsLevel.lv30Boss][1];
			break;
		case Constants.expRet_unionBat: // 帮派战
			if (retArray[type] >= ConstantsExpRet.expRetMaxTimes[type]) { // ||
																			// retArray[0]
																			// <
																			// ConstantsLevel.lv23UnionCreate
				return null;
			}
			if (player.getUnionId() <= 0) { // 没有参加帮派不能找回
				return null;
			}
			exp = (ConstantsExpRet.expRetUnionBat[retArray[0] - ConstantsLevel.lv27ExpRetrieve][0]) * rate / 100;
			costGold = ConstantsExpRet.expRetUnionBat[retArray[0] - ConstantsLevel.lv27ExpRetrieve][1];
			break;
		case Constants.expRet_sit: // 双别打坐
			if (retArray[type] >= ConstantsExpRet.expRetMaxTimes[type]) { // ||
																			// retArray[0]
																			// <
																			// ConstantsLevel.lv1OnlineExp
				return null;
			}
			exp = (ConstantsExpRet.expRetOnline[retArray[0] - ConstantsLevel.lv27ExpRetrieve][0]) * rate / 100;
			costGold = ConstantsExpRet.expRetOnline[retArray[0] - ConstantsLevel.lv27ExpRetrieve][1];
			break;
		case Constants.expRet_quiz: // 答题
			if (retArray[type] >= ConstantsExpRet.expRetMaxTimes[type]) { // ||
																			// retArray[0]
																			// <
																			// ConstantsLevel.lv13Quiz
				return null;
			}
			exp = (ConstantsExpRet.expRetQuiz[retArray[0] - ConstantsLevel.lv27ExpRetrieve]) * rate / 100;
			costGold = ConstantsExpRet.expRetQuizCost;
			break;
		case Constants.achiveRet_warpvp:
			if (retArray[type] >= ConstantsExpRet.expRetMaxTimes[type] || (retArray[0] < CampConfig.applyLevel)) {
				return null;
			}
			
			costGold = ConstantsExpRet.achiveRetWarpvpCost;
			achiveRet = retArray[0] * 18 * rate / 100;
			break;
		case Constants.achiveRet_cb:
			if (retArray[type] >= ConstantsExpRet.expRetMaxTimes[type] || (retArray[0] < ConstantsLevel.lv30CityBattle)) {
				return null;
			}
			achiveRet = retArray[0] * 20 * rate / 100;
			costGold = ConstantsExpRet.achiveRetCBCost;
			break;
		}

		// 扣除消费
		if (retType == 1) {
			costAsset = costGold * ConstantsExpRet.retAssetCostBase;
			if (player.getAsset() < costAsset) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.asset"));
			}
			player.alterAsset(-costAsset);
		} else {
			if (player.getGoldAll() < costGold) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
			}
			player.alterGoldAll(-costGold);
		}
		
		if (exp > 0) {
			player.alterExp(exp);
			player.commitSync();
		} else if (achiveRet > 0){
			player.getDataInfo().alterAchive(achiveRet);
		}
		player.getDataInfo().updateExpRetByComplete(dateTime, type); // 更新经验找回状态
		player.getDataInfo().commitSync();
		

		// 日志
		if (retType == 2) {
			// 元宝消费
			LogServer.costEventLog(session.getUid(), costGold, ConstantsCost.expRetrieve);
		}
		LogServer.recordLog(player, ConstantsLog.player, 30301, dateTime, type, costGold, costAsset, exp, achiveRet);

		// 返回值
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("asset", player.getAsset());
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("exp", exp);
		map.put("achiveRet", achiveRet);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 显示灵气抢夺面板
	 * 
	 * @param session
	 * @return ResponseMessage
	 * @author Skycat
	 */
	public ResponseMessage showAnimaPanel(Session session) {
		int oneNum = 0, twoNum = 0, threeNum = 0;
		long playerId = -1;
		for (int i = 1; i <= 50; i++) {
			playerId = OnlineExpAnimaWrest.getPlayerIdByIndex(i);
			if (i <= 5 && playerId > 0) {
				oneNum++;
			} else if (i > 5 && i <= 20 && playerId > 0) {
				twoNum++;
			} else if (i > 20 && playerId > 0) {
				threeNum++;
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("1", oneNum); // 紫气东来
		map.put("2", twoNum); // 天降祥瑞
		map.put("3", threeNum); // 绿野仙踪
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 显示灵气抢夺列表
	 * 
	 * @return ResponseMessage
	 * @author Skycat
	 */
	public ResponseMessage showAnimaList(Session session, int type) {
		if (type < 1 || type > 3) {
			return null;
		}
		int start = 1, end = 5;
		if (1 == type) {
			end = 5;
		} else if (2 == type) {
			start = 6;
			end = 20;
		} else {
			start = 21;
			end = 50;
		}

		List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>(end - start + 1);
		int idx = 1;
		for (int i = start; i <= end; i++) {
			long playerId = OnlineExpAnimaWrest.getPlayerIdByIndex(i);
			HashMap<String, Object> temp = new HashMap<String, Object>();
			temp.put("idx", idx);
			temp.put("playerId", playerId);
			if (playerId > 0) {
				Player player = Context.getPlayerServer().getByPlayerId(playerId);
				temp.put("playerName", player.getPlayerName());
				temp.put("level", player.getLevel());
			}
			list.add(temp);
			idx++;
		}
		return ResponseMessage.getSuccMessage(list);
	}

	/**
	 * 退出灵气抢夺位置
	 * 
	 * @param session
	 * @return ResponseMessage
	 * @author Skycat
	 */
	public ResponseMessage exitAnima(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int index = OnlineExpAnimaWrest.isAnimalStatus(player.getPlayerId());
		if (-1 == index) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.onlineExp.notIn"));
		}

		// 获取打坐经验
		int exp = Context.getGeneralServer().getOnlineExp(player);
		if (exp > 0) {
			player.commitSync();
		}

		// 更新该位置玩家id
		OnlineExpAnimaWrest.remove(index);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("exp", exp);
		map.put("s", 1);
		map.put("idx", OnlineExpAnimaWrest.getClientIndex(index));
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 日常队列
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage dailyQueue(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Map<String, Object> rsMap = new HashMap<String, Object>();
		// 独门劲功
		List<Queue> queues = Context.getQueueServer().getQueueIds(session.getUid(), false);
		Queue queue = null;
		if (queues != null && !queues.isEmpty()) {
			Iterator<Queue> it = queues.iterator();
			while (it.hasNext()) {
				Queue queue2 = (Queue) it.next();
				if (queue2.getType() == ConstantsQueue.typeOnGest) {
					queue = queue2;
					break;
				}
			}
			rsMap.put("gestEndTime", queue == null ? 0 : queue.getEndTime());
			rsMap.put("gestCost", DiscipleConfig.gestCost);
			rsMap.put("fastAmt", ConstantsModel.accelerateSecondOfGold);
			rsMap.put("discipleId", queue == null ? 0 : queue.getParam1());
		} else {
			PlayerMartial playerMartial = Context.getDiscipleServer().getByPlayerId(session.getUid());
			ArrayList<Disciple> list = new ArrayList<Disciple>(playerMartial.getDisciples());
			Collections.sort(list, new DiscipleCompararor());
			boolean haveMatch = false;
			if (player.getLevel() >= 50 && !BlankUtils.isBlank(playerMartial.getDisciples())) {

				for (Disciple e : list) {
					if (e.getGestSign() >= 81) {
						continue;
					}
					int indexId = NumberProcesser.ceil(e.getGestSign() + 1, 9) - 1;
					int deamId = NumberProcesser.floor(player.getDataInfo().intDataGet(ConstantsIntKey.dreamId) - 1000, 9);
					if (indexId >= deamId) {
						continue;
					}
					int levelNeed = 50 + indexId * 5;
					if (e.getLevel() < levelNeed) {
						continue;
					}
					rsMap.put("discipleId", e.getId());
					haveMatch = true;
					break;
				}
				if (!haveMatch) {
					rsMap.put("discipleId", list.get(0).getId());
				}

			}
		}

		// 副本
		Collection<Undercity> undercities = Context.getUndercityServer().getuUndercities();
		int timesMax = 0;
		int enterTimes = 0;
		int singleCount = 0;
		int teamCount = 0;

		for (Undercity e : undercities) {
			if (e.getLevel() > player.getLevel() || e.getLevelMax() < player.getLevel()) {
				continue;
			}
			timesMax = e.getTimes();
			enterTimes = player.getDataInfo().getEveryDay().getUndercityTimes(e.getId());
			if (e.getType() == Undercity.typeSingle) {
				if (player.getKnight() != null) {
					timesMax += player.getKnight().getSignleUndercityTimes();
				}
				if (enterTimes < timesMax) {
					singleCount += timesMax - enterTimes;
				}
			} else if (e.getType() == Undercity.typeTeam) {
				if (enterTimes < timesMax) {
					teamCount += timesMax - enterTimes;
				}
			}
		}
		rsMap.put("singleCount", singleCount);
		rsMap.put("teamCount", teamCount);

		// 通天图
		if (player.getLevel() >= 45) {
			if ((ConstantsModel.undercityPicCpEnterLimit > player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.ucPCpEn))) {
				rsMap.put("picCp", true);
				rsMap.put("pCpEnterTimes", player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.ucPCpEn));
			}
		}

		// 神兵阵
		Undercity city = null;
		city = Context.getUndercityServer().getUndercity(901);
		int buyNum = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.ucSCpBuyEn);

		int buyLimit = 0;
		if (player.getKnightLevel() >= ConstantsModel.undercityScpVipLevel) {
			buyLimit = ConstantsModel.undercitySoldierCpBuyNum[player.getKnightLevel() - ConstantsModel.undercityScpVipLevel];
		}
		if (city.getLevel() <= player.getLevel()) {
			if (city.getTimes() + buyNum > player.getDataInfo().getEveryDay().getUndercityTimes(city.getId()) || buyLimit - buyNum > 0) {
				rsMap.put("solCp", true);
				rsMap.put("sCpTimes", city.getTimes() + buyNum);
				rsMap.put("sCpEnterTimes", player.getDataInfo().getEveryDay().getUndercityTimes(city.getId()));
			}
		}

		// 武林大会
		if (player.getLevel() >= ConstantsLevel.lv25Challenge) {
			int challengeEndTime = player.getDataInfo().intDataGet(ConstantsIntKey.endTime);
			int challengeCount = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.challengeCount);
			int buyCount = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.challengeBuy);
			int totalTimes = ConstantsModel.challengeNum + buyCount;
			if (player.getKnight() != null) {// 武状元增加次数
				totalTimes += player.getKnight().getPvpTimes();
			}
			if(challengeCount < totalTimes) {
				rsMap.put("buyCount", buyCount);
				rsMap.put("challengeCount", challengeCount);
				rsMap.put("challengeEndTime", challengeEndTime);
				rsMap.put("totalTimes", totalTimes);
			}
		}

		// 主仆乐
		if (player.getLevel() >= ConstantsLevel.lv25Livery) {
			Livery livery = liveryManager.getFreashLivery(session.getUid());
			int todayExp = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lExp);
			int expMax = ConstantsModel.liveryMaxExp[player.getLevel() - ConstantsLevel.lv25Livery];
			if(todayExp < expMax) {
				int revoltTimes = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lRevolt);
				int revoltTotal = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lRevoltBuy) + ConstantsModel.liveryRevoltLimit;
				rsMap.put("cardId", livery.getCardId());
				rsMap.put("todayExp", todayExp);
				rsMap.put("expMax", expMax);
				rsMap.put("leaveRevolt", revoltTotal - revoltTimes);
			}
		}
		
		//周游天下
		PlayerMartial playerMartial = Context.getDiscipleServer().getByPlayerId(session.getUid());
		if (playerMartial != null) {
			Collection<Disciple> disciples = playerMartial.getDisciples();
			for (Disciple e : disciples) {
				if (e.getLevel() >= 60 && e.getLevel() < player.getLevel()) {
					rsMap.put("tour", true);
					break;
				}
			}
		}
		return ResponseMessage.getSuccMessage(rsMap);
	}
	/**
	 * 收藏好礼
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage collectLink(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv09collink) {
			return null;
		}
		boolean collected = (player.getDataInfo().intDataGet(ConstantsIntKey.comm) & 1 << 0) > 0;
		if (collected) {
			return null;
		}
		if (!player.getPlayerBoxs().checkBlack(1)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", 1));
		}
		Context.getGoodsServer().giveGoodsBing(session.getUid(), 103522, 1, 1);
		player.getDataInfo().intDataSet(ConstantsIntKey.comm, (player.getDataInfo().intDataGet(ConstantsIntKey.comm) | 1 << 0));
		player.getDataInfo().commitSync();
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(103522);
		LogServer.recordLog(player, ConstantsLog.activity, 90013, goodsMode.getName(), 1);
		return ResponseMessage.getSuccMessage(true);
	}
}